﻿;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Logistics.WaybillReconciliation", [])
        .controller("WaybillReconciliationCtrl", ["$scope", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "$filter", "UserContextService", function ($scope, ybWidget, ybHttp, MESG_TYPE, $timeout, $filter, UserContextService) {
            $scope.activeFlag = [true, false, false, false, false];
            $scope.markInfo = {
                allCheckedWayBill: false,
                allCheckedBill: false,
                allCheckedMaterial: false
            };
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
            };

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
            };

            function checkAll(list) {
                var selectAllFlag = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAllFlag = false;
                        break;
                    }
                    selectAllFlag = true;
                }
                return selectAllFlag;
            }

            $scope.curStep = { val: 0 };

            $scope.submitted = false;

            $scope.tabFlag = {};
            var tabFlag = {
                0: "新增",
                1: "编辑",
                2: "审核",
                3: "审批",
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/deliveryNote/exportDetails"),
                sectionParam: { ids: [] },
                allUrl: ybHttp.RequestUrl("device", "/deliveryNote/exportDetailsAll")
            };

            $scope.tableConfig = {
                fixedWidth: 220,
                scrollWidth: 1630,
                tableCol: [
                    {
                        name: "结算单号",
                        dataField: "wayBillFeeNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn:"viewDetail",
                    },
                    {
                        name: "总运费",
                        dataField: "totalFee",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "审核后总运费",
                        dataField: "afterAuditTotalFee",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "运输方式",
                        dataField: "shippingMethod",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "单据状态",
                        dataField: "statusShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "制单人",
                        dataField: "createUserName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "制单时间",
                        dataField: "createDateShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "审核人",
                        dataField: "auditUserName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "审核时间",
                        dataField: "auditDateShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "审批人",
                        dataField: "approvalUserName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "审批时间",
                        dataField: "approvalDateShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        width: 180,
                        isShow: true,
                        isFixed: true,
                    }
                ]
            };

            $scope.detailTbConf = {
                scrollWidth: 1400,
                tableCol: [
                    {
                        name: "物流运单号",
                        dataField: "wayBillNo",
                        width: 180,
                        clickFn: 'viewWayBill',
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "客户名称",
                        dataField: "dealerOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "业务单号",
                        dataField: "businessOrderNos",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "初始运费",
                        dataField: "initinalCarriage",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "变更后运费",
                        dataField: "afterModifyCarriage",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "最终运费",
                        dataField: "finalCarriage",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "发运方式",
                        dataField: "shippingMethod",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "承运商",
                        dataField: "carrierOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                ]
            };

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    }
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.markInfo = {
                    allCheckedWayBill: false,
                    allCheckedBill: false,
                };
                $scope.curStep = { val: 0 };
                $scope.billPageInfo = {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                };
                $scope.billCondition = {};
                $scope.billDataList = [];
                $scope.orderObj = {};
                $scope.submitted = false;
            }


            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.dataList = [];
            $scope.reset = function () {
                $scope.condition = {};
            };
            $scope.search = function (curpage) {
                getDataList(curpage);
            };
            function getDataList(curPage) {
                var service = "device";
                var reqUrl = "/logisticWaybillFee/listing";
                var param = {};
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageSize = $scope.pageInfo.pageSize;
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.statusShow = $filter("WayBillStatus2")(item.status);
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.auditDateShow = $filter("YbDate")(item.auditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.approvalDateShow = $filter("YbDate")(item.approvalDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }
            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.addData = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];
                $scope.changeTab(1);
            };

            $scope.billPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.billCondition = {};
            $scope.billDataList = [];
            $scope.billSearch = function () {
                if (!$scope.billCondition.shippingMethodId) {
                    ybWidget.ShowToaster('error', '请选择发运方式');
                    return
                }
                if (!$scope.billCondition.billType) {
                    ybWidget.ShowToaster('error', '请选择单据类型');
                    return
                }
                getBillsData();
            };

            function getBillsData(curPage) {
                var service = "device";
                var reqUrl = "/logisticWaybillFee/waybillsSelect";
                var param = {};
                if (!!curPage) {
                    $scope.billPageInfo.curPage = curPage;
                }
                param.pageSize = $scope.billPageInfo.pageSize;
                param.pageNum = $scope.billPageInfo.curPage;
                param.filters = angular.copy($scope.billCondition);
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                    });
                    $scope.billPageInfo.totalRows = resp.value.total;
                    $scope.billPageInfo.totalPages = resp.value.pages;
                    $scope.billDataList = resp.value.list;
                });
            }

            $scope.selectedBillDataList = [];

            $scope.nextStep = function () {
                var arr = $scope.billDataList.filter(f=>f.isChecked)
                if (arr.length == 0) {
                    ybWidget.ShowToaster('error', '请选择单据');
                    return
                }
                $scope.selectedBillDataList = arr
                $scope.curStep.val = 1;
            };

            $scope.delSelectBills = function (index) {
                $scope.selectedBillDataList.splice(index, 1);
            };

            $scope.$watch('selectedBillDataList', function () {
                $scope.finalCarriageTotal = $scope.selectedBillDataList.reduce((total, cur) => {
                    return total + Number(cur.finalCarriage||0)
                },0)
            }, true);

            $scope.saveData = function (type) {
                if ($scope.selectedBillDataList.length == 0) {
                    ybWidget.ShowToaster('error', '没有单据');
                    return;
                }

                var service = "device";
                var reqUrl = "/logisticWaybillFee/save";
                if (type == 'submit') {
                    reqUrl = "/logisticWaybillFee/submit";
                }

                var param = {
                    headInfo: {
                        id: $scope.orderObj.headInfo ? $scope.orderObj.headInfo.id : '',
                        shippingMethodId: $scope.selectedBillDataList[0].shippingMethodId,
                        shippingMethod: $scope.selectedBillDataList[0].shippingMethod,
                        totalFee: $scope.finalCarriageTotal,
                    },
                    details: $scope.selectedBillDataList
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.delData = function (val) {
                var service = "device";
                var reqUrl = "/logisticWaybillFee/remove";
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Get(service, reqUrl, { id: val }).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                }, function () {})
            };

            // 编辑/审核/审批 获取结算单详情
            function viewInfo(val) {
                var service = "device";
                var reqUrl = "/logisticWaybillFee/viewInfo";
                return ybHttp.Get(service, reqUrl, { id: val }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value
                });
            }

            $scope.editData = function(val) {
                viewInfo(val).then((value) => {
                    if (!value) {
                        return
                    }

                    $scope.orderObj = value

                    $scope.finalCarriageTotal = value.headInfo.totalFee;
                    $scope.selectedBillDataList = value.details;

                    $scope.curStep.val = 1;
                    $scope.tabFlag.type = 1;
                    $scope.tabFlag.name = tabFlag[1];
                    $scope.changeTab(1);
                })
            };

            $scope.orderObj = {};
            $scope.auditData = function(val) {
                viewInfo(val).then((value) => {
                    if (!value) {
                        return
                    }
                    $scope.orderObj = value;
                    $scope.tabFlag.type = 2;
                    $scope.tabFlag.name = tabFlag[2];
                    $scope.changeTab(3);
                })
            };
            $scope.alterationRatioChange = function() {
                var str = '' + $scope.orderObj.headInfo.alterationRatio;
                if (str === 'undefined') return;
                if (str.lastIndexOf('.') === str.length - 1) return;
                if (str.lastIndexOf('-') === str.length - 1) return;
                if (Number(str)<-5 || Number(str)>5) return;

                $scope.orderObj.headInfo.afterAuditTotalFee = (($scope.orderObj.headInfo.totalFee||0)*(100+Number(str))/100).toFixed(2);
            };

            $scope.approveData = function(val) {
                viewInfo(val).then((value) => {
                    if (!value) {
                        return
                    }
                    $scope.orderObj = value;
                    $scope.tabFlag.type = 3;
                    $scope.tabFlag.name = tabFlag[3];
                    $scope.changeTab(3);
                })
            };
            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };
            $scope.handleAudit = function(isValid, type, ids, msg) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "";

                var param = {
                    ids: ids || [$scope.orderObj.headInfo.id]
                };
                var auditMsg = msg || ($scope.orderObj.headInfo ? $scope.orderObj.headInfo.auditRemark : '');

                if ($scope.tabFlag.type == 2) {
                    if (!auditMsg) {
                        ybWidget.ShowMessage("请输入审核意见", MESG_TYPE.Error);
                        return;
                    }

                    // 审核
                    if (type == '1') {
                        reqUrl = "/logisticWaybillFee/auditPass";
                    } else if (type == '2') {
                        reqUrl = "/logisticWaybillFee/auditReject";
                    }
                    param.auditRemark = auditMsg;
                    
                    if ($scope.orderObj.headInfo) {
                        param.alterationRatio = $scope.orderObj.headInfo.alterationRatio
                        param.afterAuditTotalFee = $scope.orderObj.headInfo.afterAuditTotalFee
                    }
                    // 审核的时候还需传递 alterationRatio、afterAuditTotalFee(批量操作时 怎么交互？？？)：实施回复 批量审核时不用管这些
                } else if ($scope.tabFlag.type == 3) {
                    if (!auditMsg) {
                        ybWidget.ShowMessage("请输入审批意见", MESG_TYPE.Error);
                        return;
                    }

                    // 审批
                    if (type == '1') {
                        reqUrl = "/logisticWaybillFee/approvalPass";
                    } else if (type == '2') {
                        reqUrl = "/logisticWaybillFee/approvalReject";
                    }
                    param.approvalRemark = auditMsg;
                }

                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };


            $scope.auditBillBatch = function (type) {
                var typeName = type == 2 ? '审核' : type == 3 ? '审批' : '';
                $scope.tabFlag.type = type;

                var ids = [];
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        ids.push($scope.dataList[i].id);
                    }
                }
                if (ids.length === 0) {
                    ybWidget.ShowMessage(`请正确选择需要${typeName}的行`);
                    return;
                }
                ybWidget.AuditMsg({
                    title: typeName,
                    passCb: function(val) {
                        if (!val) {
                            ybWidget.ShowMessage(`请填写${typeName}意见`, MESG_TYPE.Error);
                            return Promise.reject();
                        }
                        return $scope.handleAudit(true, 1, ids, val)
                    },
                    refuseCb: function(val) {
                        return $scope.handleAudit(true, 2, ids, val)
                    }
                })
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewWayBill":
                        ybWidget.LogisticsWaybillDetail({wayBillId:item.wayBillId});
                        break;
                    case "viewDetail":
                        viewDetail(item)
                        break;
                    default:
                        break;
                }
            };

            $scope.printSingle = function (val) {
                var billIds = [val];
                var param = {
                    billId: billIds,
                    printType: "WaybillReconciliation"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            // 点击运费结算单查看详情
            function viewDetail(item) {
                var service = "device";
                var reqUrl = "/logisticWaybillFee/viewInfo";
                ybHttp.Get(service, reqUrl, { id: item.id }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailInfo = resp.value;
                    $scope.changeTab(2);

                });
            }

            // 查询运输方式
            function getSendMethods () {
                var service = "device";
                var reqUrl = "/sendMethodDictionary/list";
                var param = {pId: 0};
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.sendMethodList = resp.value;
                })
            }

            var btnPermissionCode = {
                waybillReconciliationEdit: window.ActionCode.waybillReconciliationEdit,
                waybillReconciliationAudit: window.ActionCode.waybillReconciliationAudit,
                waybillReconciliationApprove: window.ActionCode.waybillReconciliationApprove,
                waybillReconciliationDel: window.ActionCode.waybillReconciliationDel,
                waybillReconciliationPrint: window.ActionCode.waybillReconciliationPrint,
            };

            $scope.btnPermission = {
                waybillReconciliationEdit: true,
                waybillReconciliationAudit: true,
                waybillReconciliationApprove: true,
                waybillReconciliationDel: true,
                waybillReconciliationPrint: true,
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            (function () {
                getDataList();
                getSendMethods();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }]);
})(window, window.angular);
